//
//  Contacter.m
//  Contacts
//
//  Created by nsm on 2017/10/16.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "Contacter.h"

@implementation Contacter

- (NSString *)name {
    return _name? _name: @"";
}

- (NSArray *)phones {
    return _phones? _phones: @[];
}

+ (instancetype)contacterWithRecordRef:(ABRecordRef)ref {
    return [[self alloc] initWithRecordRef:ref];
}

+ (instancetype)contacterWithCNContact:(CNContact *)contact {
    return [[self alloc] initWithCNContact:contact];
}

- (instancetype)initWithRecordRef:(ABRecordRef)ref {
    self = [super init];
    if (self) {
        self.name = CFBridgingRelease(ABRecordCopyCompositeName(ref));
        
        ABMultiValueRef valueRef = ABRecordCopyValue(ref, kABPersonPhoneProperty);
        CFIndex count = ABMultiValueGetCount(valueRef);
        NSMutableArray *phones = [NSMutableArray array];
        for (CFIndex i = 0; i < count; i++) {
            NSString *number = CFBridgingRelease(ABMultiValueCopyValueAtIndex(valueRef, i));
            [phones addObject:[self filterSpecialString:number]];
        }
        CFRelease(valueRef);
        self.phones = phones;
    }
    return self;
}

- (instancetype)initWithCNContact:(CNContact *)contact NS_AVAILABLE_IOS(9_0) {
    self = [super init];
    if (self) {
        self.name = [CNContactFormatter stringFromContact:contact style:CNContactFormatterStyleFullName];
        
        if ([contact isKeyAvailable:CNContactPhoneNumbersKey]) {
            NSMutableArray *phones = [NSMutableArray array];
            for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
                CNPhoneNumber *number = labeledValue.value;
                [phones addObject:[self filterSpecialString:number.stringValue]];
            }
            self.phones = phones;
        }
    }
    return self;
}

- (NSString *)filterSpecialString:(NSString *)string {
    if (!string) return @"";
    
    string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return string;
}

@end
